import 'dart:ffi';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_fronter_service/model/address_entity.dart';
import 'package:flutter_fronter_service/model/sku_entity.dart';
import 'package:flutter_fronter_service/tools/commons.dart';
import 'package:get/get.dart';

import '../api/goodsApi.dart';
import '../api/orderApi.dart';
import '../model/properties_entity.dart';
class ConfirmOrderPage extends StatefulWidget {
  const ConfirmOrderPage({super.key});

  @override
  State<ConfirmOrderPage> createState() => _ConfirmOrderPageState();
}

class _ConfirmOrderPageState extends State<ConfirmOrderPage> {


  late Rx<double> totalPrice = 0.0.obs;
  //地址信息
  late AddressEntity addressEntity = AddressEntity();

  //订单信息
  late List<Map<String,dynamic>> dataList = [];

  //购物车id列表
  late List<int> cartIdList = [];
  Future<void> getSkuData() async {

    for(int i = 0;i<Get.arguments["sku"].length;i++){

      if(Get.arguments["sku"][i].containsKey("cartId")){
        cartIdList.add(Get.arguments["sku"][i]["cartId"]);
      }

      //获取sku信息
      late SkuEntity skuEntity;
      late RxList<PropertiesEntity> itemSpecList = <PropertiesEntity>[].obs;
      Map<String,dynamic> map = {};
      late Rx<String> goodsSpec = "".obs;
      //解析
      map["quantity"] = Get.arguments["sku"][i]["count"];

      //获取请求
      var res = await getSkuById(Get.arguments["sku"][i]["id"]);
      //解析请求
      map["goodsPrice"] = res["data"].remove("goodsPrice");
      map["goodsName"] = res["data"].remove("goodsName");
      res["data"]["itemSpec"].forEach((item)=>itemSpecList.add(PropertiesEntity.fromJson(item)));
      //解析sku
      skuEntity = SkuEntity.fromJson(res["data"]);
      skuEntity.itemSpec =  itemSpecList;
      map["sku"] = skuEntity;
      //解析规格
      itemSpecList.forEach((element) {
        goodsSpec.value = goodsSpec.value +' '+ element.value;
      });
      map["goodsSpec"] = goodsSpec.value;

      //计算总价
      totalPrice.value = totalPrice.value + (map["quantity"] * map["goodsPrice"]);
      dataList.add(map);

      print(cartIdList);
    }
    setState(() {
    });
  }

  @override
  void initState() {
    super.initState();
    getSkuData();

  }

  @override
  Widget build(BuildContext context) {

    double shippingFee = 5.0;


    return  Scaffold(
      appBar: AppBar(
        title: Text('确认订单'),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            // 收货地址
            Card(
              margin: EdgeInsets.only(bottom: 16),
              child: ListTile(
                title: Text(addressEntity.contactName.isNotEmpty?addressEntity.contactName:"请选择地址"),
                subtitle: Text(addressEntity.province.isNotEmpty?
                '${addressEntity.province}${addressEntity.city}${addressEntity.district}${addressEntity.address}\n${addressEntity.contactTel}':""),
                trailing: Icon(Icons.arrow_forward_ios),
                onTap: () {
                  Get.toNamed("/deliveryAddress")!.then((value) {
                    setState(() {
                      addressEntity = value;
                    });
                  });
                },
              ),
            ),
            // 商品信息
            Card(
              margin: EdgeInsets.only(bottom: 16),
              child: Column(
                children: [
                  ...dataList.map((e) => ItemCard(dataMap: e)),
                  Divider(),
                  const ListTile(
                    title: Text('备注'),
                    subtitle: TextField(
                      decoration: InputDecoration(
                        hintText: '填写备注',
                        border: InputBorder.none,
                      ),
                      maxLines: 2,
                    ),
                  ),
                  Divider(),
                  ListTile(
                    title: Text('配送时间'),
                    subtitle: DropdownButton<String>(
                      isExpanded: true,
                      value: '工作日',
                      onChanged: (String? newValue) {
                        // 处理选择
                      },
                      items: <String>['工作日', '周末']
                          .map<DropdownMenuItem<String>>((String value) {
                        return DropdownMenuItem<String>(
                          value: value,
                          child: Text(value),
                        );
                      }).toList(),
                    ),
                  ),
                ],
              ),
            ),
            // 运费和总价
            Card(
              margin: EdgeInsets.only(bottom: 16),
              child: Column(
                children: [
                  ListTile(
                    title: Text('运费'),
                    trailing: Text('￥$shippingFee'),
                  ),
                  Divider(),
                  ListTile(
                    title: Text('商品价格'),
                    trailing: Text('￥${totalPrice.value.toString()}'),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      bottomNavigationBar: Container(
        padding: EdgeInsets.all(16),
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text(
              '总价：￥${totalPrice.value + shippingFee}',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            ElevatedButton(
              onPressed: () async {
                if(addressEntity.id > 0){
                  //构建DTO
                  Map<String,dynamic> order = {
                    "addressId":addressEntity.id,
                    "orderRemark":"无",
                    "deliveryTime":"周末",
                    "isCart":false,
                    "cartIds":[],
                    "orderItems":dataList.map((e) => {"skuId":e["sku"].id,"quantity":e["quantity"]}).toList()
                  };
                  if(cartIdList.length > 0){
                    order["cartIds"] = cartIdList;
                    order["isCart"] = true;
                  }
                  var res = await saveOrdersApi(order);
                  if(res["data"].runtimeType.toString()=="_Map<String, dynamic>"&&res["data"]["id"] >0){
                    Get.offNamedUntil("/orderDetail",(route) => false,arguments: {"id":res["data"]["id"]});
                  }else{
                    CommonUtils.showBotToast("创建失败");
                  }
                }else{
                  CommonUtils.showBotToast("请选择地址");
                }
              },
              child: Text('提交订单'),
            ),
          ],
        ),
      ),
    );
  }
}

class ItemCard extends StatelessWidget {
  final Map<String,dynamic> dataMap;

  const ItemCard({super.key, required this.dataMap});

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: Image.network(
        dataMap["sku"].itemImg,
        width: 50,
        height: 50,
        fit: BoxFit.cover,
      ),
      title: Text(dataMap["goodsName"]),
      subtitle: Text('规格: ${dataMap["goodsSpec"]}\n数量: ${dataMap["quantity"]}'),
      trailing: Text('￥${dataMap["goodsPrice"]}'),
    );
  }
}
